package com.cloud.servlet;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloud.core.BaseServlet;
import com.cloud.core.emchat.ChatAdmin;
import com.cloud.core.redis.RedisClient;
import com.cloud.core.sms.SmsService;
import com.cloud.dao.UserBean;
import com.cloud.service.UserService;
import com.cloud.util.Code;
import com.cloud.util.CommUtil;
import com.cloud.util.TokenUtil;
import com.google.gson.JsonObject;

/**
 * 1Cloud1
 * @author Administrator
 * @since 2015-11-4
 * @version 1.0 
 */
@Controller
@RequestMapping("/register")
public class RegisterServlet extends BaseServlet {
	private static final Logger logger = LoggerFactory.getLogger(RegisterServlet.class);
	private final String code_prefix = CommUtil.code_prefix;
	private final String code_time_prefix = CommUtil.code_time_prefix;
	
	@Autowired
	private UserService UserService;
	
	@Autowired
	private ChatAdmin ChatAdmin;
	
	@Autowired
	private SmsService SmsService;
	
	@Autowired
	private RedisClient RedisClient;
	
	/**
	 * 邀请码
	 * @param request
	 * @param phone
	 * @param token
	 * @param event
	 * @return
	 */
	@RequestMapping(value = "/invite", method = { RequestMethod.GET})
	public @ResponseBody Object invite(HttpServletRequest request, String phone, String token, String event) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(CommUtil.isEmpty(phone) || CommUtil.isEmpty(token)){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		UserBean _user = new UserBean();
		_user.setUserName(phone);
		List<UserBean> _list = UserService.getUserList(_user);
		if(CommUtil.isEmpty(event)){
			if(_list != null && _list.size() > 0){
				map.put("code", Code.C410.key);
				map.put("msg", Code.C410.desc);
				return map;
			}
		} else if("0".equals(event)){
			if(_list != null && _list.size() < 1){
				map.put("code", Code.C420.key);
				map.put("msg", Code.C420.desc);
				return map;
			}
		}
		logger.info(String.format("[%s]调用接口发送验证码,Token：[%s]", phone, token));
		String keynum = code_time_prefix.concat(phone);
		token = token.toLowerCase();
		if(TokenUtil.tokenVerification(phone, token)){
			List<String> indexList = RedisClient.lrange(keynum);
			if(indexList.contains(token)){
				map.put("code", Code.C414.key);
				map.put("msg", Code.C414.desc);
				return map;
			}
			if(indexList.size() > 5){
				map.put("code", Code.C415.key);
				map.put("msg", Code.C415.desc);
				return map;
			}
		} else {
			map.put("code", Code.C416.key);
			map.put("msg", Code.C416.desc);
			return map;
		}
		String key = code_prefix.concat(phone);
		String code = CommUtil.vcode(6);
		boolean send = true; //SmsService.sendSms(phone, code);
		if(send){
			logger.info(String.format("写人[%s]的验证码消息到Redis[%s]", phone, code.concat("_init")));
			RedisClient.setString(key, code.concat("_init"), Integer.valueOf(SmsService.getInviteTempletValid()));
			RedisClient.rpush(keynum, token, Integer.valueOf(SmsService.getInviteTempletValid()));
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
	
	/**
	 * 验证邀请码
	 * @param request
	 * @param phone
	 * @param invite
	 * @return
	 */
	@RequestMapping(value = "/invite/validated", method = { RequestMethod.GET})
	public @ResponseBody Object invitevalidated(HttpServletRequest request, String phone, String invite) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(CommUtil.isEmpty(phone) || CommUtil.isEmpty(invite)){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		String key = code_prefix.concat(phone);
		String code = RedisClient.get(key);
		logger.info(String.format("验证[%s]的验证码[%s] Redis取出[%s]", phone, invite, code));
		if(!CommUtil.isEmpty(code) && invite.equals(code.split("_")[0]) && "init".equals(code.split("_")[1])){
			RedisClient.setString(key, code.split("_")[0].concat("_ok"), 1800); //30分钟
		} else {
			map.put("code", Code.C417.key);
			map.put("msg", Code.C417.desc);
			return map;
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
	
	@RequestMapping(value = "/add", method = { RequestMethod.POST})
	public @ResponseBody Object register(HttpServletRequest request, @RequestBody UserBean user) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(user == null || CommUtil.isEmpty(user.getUserName()) || CommUtil.isEmpty(user.getPassWord()) || CommUtil.isEmpty(user.getClientType())){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		//是否发送验证码校验
		boolean isSend = Boolean.valueOf(CommUtil.isEmpty(SmsService.getSmssend()) ? "true" : SmsService.getSmssend());
		String key = code_prefix.concat(user.getUserName());
		String keynum = code_time_prefix.concat(user.getUserName());
		if(isSend){
			String code = RedisClient.get(key);
			logger.info(String.format("验证[%s]注册是否验证过手机 Redis取出[%s]", user.getUserName(), code));
			boolean isValid = !CommUtil.isEmpty(code) && "ok".equals(code.split("_")[1]);
			if(!isValid){
				map.put("code", Code.C413.key);
				map.put("msg", Code.C413.desc);
				return map;
			}
		}
		UserBean _user = new UserBean();
		_user.setUserName(user.getUserName());
		if(UserService.getUserList(_user).size() > 0){
			map.put("code", Code.C410.key);
			map.put("msg", Code.C410.desc);
			return map;
		}
		user.setMd5Pwd(CommUtil.MD5(user.getPassWord()));
		JsonObject obj = ChatAdmin.createSingleUser(user.getUserName(), user.getPassWord(), user.getNikeName());
		if(!obj.toString().toLowerCase().contains("activated")){
			map.put("code", Code.C411.key);
			map.put("msg", Code.C411.desc);
			return map;
		}
		if(CommUtil.isEmpty(user.getFullname())){
			user.setFullname(user.getUserName());
		}
		if(CommUtil.isEmpty(user.getMobile())){
			user.setMobile(user.getUserName());
		}
		UserService.addUser(user);
		if(isSend){
			RedisClient.del(keynum);
			RedisClient.del(key);
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
	
	/**
	 * 解绑手机号
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/release/bound", method = { RequestMethod.POST})
	public @ResponseBody Object releasebound(HttpServletRequest request, @RequestBody UserBean user) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(user == null || CommUtil.isEmpty(user.getUserName()) || CommUtil.isEmpty(user.getPassWord()) || CommUtil.isEmpty(user.getMobile())){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		String key = code_prefix.concat(user.getMobile());
		String keynum = code_time_prefix.concat(user.getMobile());
		String code = RedisClient.get(key);
		logger.info(String.format("解绑手机号[%s]为[%s]  Redis取出code为[%s]", user.getUserName(), user.getMobile(), code));
		if(!CommUtil.isEmpty(code) && "ok".equals(code.split("_")[1])){
			UserBean _user = new UserBean();
			_user.setUserName(user.getUserName());
			_user.setMd5Pwd(CommUtil.MD5(user.getPassWord()));
			List<UserBean> retUserList = UserService.getUserList(_user);
			if(retUserList == null || retUserList.size() < 1){
				map.put("code", Code.C400.key);
				map.put("msg", Code.C400.desc);
				return map;
			}
			_user = null;
			_user = new UserBean();
			_user.setUserName(user.getMobile());
			List<UserBean> _retUserList = UserService.getUserList(_user);
			if(_retUserList.size() > 0){
				map.put("code", Code.C410.key);
				map.put("msg", Code.C410.desc);
				return map;
			}
			JsonObject obj = ChatAdmin.createSingleUser(user.getMobile(), user.getPassWord(), retUserList.get(0).getNikeName());
			if(!obj.toString().toLowerCase().contains("activated")){
				map.put("code", Code.C411.key);
				map.put("msg", Code.C411.desc);
				return map;
			}
			ChatAdmin.deleteUser(user.getUserName());
			_user = null;
			_user = new UserBean();
			_user.setUserName(user.getMobile());
			_user.setUserId(retUserList.get(0).getUserId());
			_user.setMobile(user.getMobile());
			UserService.updateUser(_user, true);
			RedisClient.del(keynum);
			RedisClient.del(key);
			map.put("code", Code.C200.key);
			map.put("msg", Code.C200.desc);
			return map;
		}
		map.put("code", Code.C413.key);
		map.put("msg", Code.C413.desc);
		return map;
	}
}
